package com.corner.system.task;

import com.corner.common.enums.BatchCloseReason;
import com.corner.common.enums.BatchDetailFailReason;
import com.corner.common.enums.WxBatchDetailState;
import com.corner.system.domain.Subsidy;
import com.corner.system.domain.TransferBatches;
import com.corner.system.mapper.SubsidyMapper;
import com.corner.system.mapper.TransferBatchesMapper;
import com.corner.system.service.WxPayService;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@Component
@EnableScheduling
@EnableAsync
public class WxPayTask {

    private static final Logger log = LoggerFactory.getLogger(WxPayTask.class);
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private TransferBatchesMapper batchesMapper;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    @Autowired
    private SubsidyMapper subsidyMapper;

    @Value("${GZH_APPID}")
    private String appid;
    /*@Value("${REFUND_BATCH_FAIL_TEMPLATE}")
    private String REFUND_BATCH_FAIL_TEMPLATE;
*/
    @Bean("taskAsyncScheduler")
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(20);
        //scheduler.initialize();
        return taskScheduler;
    }

/*    @Scheduled(cron = "0/5 * * * * ? ")
    @Async("taskAsyncScheduler")
    public void test() {
        String id = Thread.currentThread().getName();
        log.info(String.format("[%s]test1...开启", id));
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info(String.format("[%s]tes1....结束", id));

    }*/

    /**
     * 商家转账到零钱
     * 超过24小时的单，状态置为失效
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    @Async("taskAsyncScheduler")
    public void checkTransferBatchStatus() {
        log.info("执行商家转账到零钱查询状态定时任务。thread id:{},thread Name:{},FixedPrintTask execute times:{}", Thread.currentThread().getId(),Thread.currentThread().getName(),new Date());
        //查询未关闭的或未完成的订单
        List<Map<String, Object>> list = batchesMapper.queryOnhandBatchs();
        for(Map<String,Object> m: list){
            String batchNo = (String)m.get("batchNo");
            int uidStr = (Integer)m.get("detailUserId");
            Long userId = Long.valueOf(uidStr);
            String deviceId = (String)m.get("deviceId");
            executor.execute(new Runnable() {
                @Transactional
                @Override
                public void run() {
                    try {
                        log.info("处理未完成单号:{}",batchNo);
                        String wxBatchId = ""; //微信批次单号
                        String batch_status = "";//批次状态
                        String close_reason = "";//批次关闭原因
                        String out_batch_no = "";//批次单号
                        String batch_update_time = "";//批次单号
                        //
                        int fail_num = 0;
                        Map<String, Object> batchResult = wxPayService.queryBatchsStatus(batchNo, "true", "ALL");
                        int statusCode = (Integer)batchResult.get("statusCode");
                        if( statusCode != 200 && statusCode != 204){
                            if(BatchCloseReason.NOT_FOUND_CLOSE.getType().equals(batchResult.get("code"))){
                                close_reason = BatchCloseReason.NOT_FOUND_CLOSE.getDesc();
                            }else {
                                close_reason= "未知错误 ！！！";
                            }
                            TransferBatches batches = new TransferBatches();
                            batches.setBatchNo(batchNo);
                            batches.setUpdateTime(new Date());//明细更新时间
                            batches.setDetailStatus("FAIL");//明细状态
                            batches.setBatchStatus("CLOSED");
                            batches.setCloseReason(close_reason);
                            batches.setFailReason(close_reason);
                            batchesMapper.updateTransferBatchesByBatchNoOrDetailNo(batches);

                            /*Subsidy subsidy = new Subsidy();
                            subsidy.setTransferBatchNo(batchNo);
                            subsidy.setStatus("2");
                            //subsidy.setRemark(close_reason);
                            subsidyMapper.updateSubsidyByBatchOrDetailNo(subsidy);*/
                            return;
                        }

                        Map transfer_batch = (Map)batchResult.get("transfer_batch");
                        batch_status = (String)transfer_batch.get("batch_status");//批次状态
                        out_batch_no = (String)transfer_batch.get("out_batch_no");//批次单号
                        batch_update_time = (String)transfer_batch.get("update_time");//批次更新时间
                        Date batch_update_time_parse = DateUtils.parseDate(batch_update_time, "yyyy-MM-dd'T'HH:mm:ssXXX");
                        BigDecimal total_amount_fen = new BigDecimal(transfer_batch.get("total_amount").toString());
                        BigDecimal total_amount_yuan = total_amount_fen.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UNNECESSARY);
                        DecimalFormat decimalFormat = new DecimalFormat("0.00#");
                        String totalamountStr = decimalFormat.format(total_amount_yuan);//批次总额（元）

                        //明细
                        List<Map> transfer_detail_list = (List<Map>)batchResult.get("transfer_detail_list");

                        //整个批次状态为关闭
                        if("CLOSED".equals(batch_status)){
                            //关闭原因
                            close_reason = (String)transfer_batch.get("close_reason");
                            if(BatchCloseReason.OVERDUE_CLOSE.getType().equals(close_reason)){
                                close_reason = BatchCloseReason.OVERDUE_CLOSE.getDesc();
                            }
                            if(BatchCloseReason.MERCHANT_REVOCATION.getType().equals(close_reason)){
                                close_reason = BatchCloseReason.MERCHANT_REVOCATION.getDesc();
                            }
                            if(BatchCloseReason.TRANSFER_SCENE_INVALID.getType().equals(close_reason)){
                                close_reason = BatchCloseReason.TRANSFER_SCENE_INVALID.getDesc();
                            }
/*                            //发送公众号提醒
                            Map requestMap = new HashMap();
                            Map data = new HashMap();

                            //数据map
                            Map first = new HashMap<>();
                            first.put("value","有一笔用户提现交易已关闭，请及时处理");
                            first.put("color","#173177");
                            data.put("first",first);

                            //1单号
                            Map thing1 = new HashMap<>();
                            thing1.put("value",out_batch_no);
                            thing1.put("color","#173177");
                            data.put("keyword1",thing1);

                            //2金额
                            Map thing2 = new HashMap<>();
                            thing2.put("value",totalamountStr);
                            thing2.put("color","#173177");
                            data.put("keyword2",thing2);

                            //3原因
                            Map thing3 = new HashMap<>();
                            thing3.put("value",close_reason);
                            thing3.put("color","#173177");
                            data.put("keyword3",thing3);
                            // 给管理员发信息
                            requestMap.put("touser","oQSeK5rNSlKygEuOTxPNVfrDZzQc");
                            requestMap.put("template_id",REFUND_BATCH_FAIL_TEMPLATE);
                            requestMap.put("data",data);
                            //公众号发送信息
                            wxgzhService.publicMsg(requestMap);*/


                            TransferBatches batches = new TransferBatches();
                            batches.setBatchNo(out_batch_no);
                            batches.setWxBatchId(wxBatchId);
                            batches.setBatchStatus(batch_status);//批单状态
                            batches.setUpdateTime(batch_update_time_parse);//明细更新时间
                            batches.setDetailStatus("FAIL");//明细状态
                            batches.setCloseReason(close_reason);
                            batches.setFailReason(close_reason);
                            batchesMapper.updateTransferBatchesByBatchNoOrDetailNo(batches);


                            Subsidy subsidy = new Subsidy();
                            subsidy.setTransferBatchNo(out_batch_no);
                            subsidy.setStatus("2");
                            subsidy.setRemark(close_reason);
                            //subsidy.setDelFlag("1");
                            subsidyMapper.updateSubsidyByBatchOrDetailNo(subsidy);

                            System.out.println("查询完成CLOSE");
                            return;
                        }
                        //fail_num = Integer.parseInt((String) transfer_batch.get("fail_num"));

                        //获取明细单信息

                        for (Map detail :transfer_detail_list){
                            //
                            String out_detail_no = (String) detail.get("out_detail_no");

                            Map<String, Object> detailMap = wxPayService.queryBatchDetailStatus(batchNo, out_detail_no);

                            String detail_id = (String) detail.get("detail_id");
                            String detail_status = (String) detail.get("detail_status");
                            //String xcxopenid = (String) detail.get("openid");
                            String initiate_time = (String) detailMap.get("initiate_time");//状态更新时间
                            String detail_update_time = (String) detailMap.get("update_time");
                            BigDecimal transfer_amount_fen = new BigDecimal(detailMap.get("transfer_amount").toString());
                            BigDecimal transfer_amount_yuan = transfer_amount_fen.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UNNECESSARY);
                            String amountStr = decimalFormat.format(transfer_amount_yuan);
                            Date detail_update_time_parse = DateUtils.parseDate(detail_update_time, "yyyy-MM-dd'T'HH:mm:ssXXX");

                            // 如果是失败的
                            if("FAIL".equals(detail_status)){
                                //获取失败原因
                                String fail_reason = (String) detailMap.get("fail_reason");
                                for(BatchDetailFailReason reason : BatchDetailFailReason.values()){
                                    if(reason.getType().equals(fail_reason)){
                                        fail_reason = reason.getDesc();
                                        break;
                                    }
                                }

                                TransferBatches batches = new TransferBatches();
                                batches.setDetailNo(out_detail_no);
                                batches.setWxBatchId(wxBatchId);
                                batches.setBatchStatus(batch_status);//批单状态
                                batches.setFailReason(fail_reason); //明细失败原因
                                batches.setUpdateTime(detail_update_time_parse);//明细更新时间
                                batches.setWxDetailId(detail_id);//微信端明细单号
                                batches.setDetailStatus(detail_status);//明细状态
                                if(close_reason != null){
                                    batches.setCloseReason(close_reason);
                                }
                                batchesMapper.updateTransferBatchesByBatchNoOrDetailNo(batches);
                                Subsidy subsidy = new Subsidy();
                                subsidy.setTransferBatchNo(out_batch_no);
                                subsidy.setTransferDetailNo(out_detail_no);
                                subsidy.setStatus("2");
                                subsidy.setRemark(fail_reason);
                                //subsidy.setDelFlag("1");
                                subsidyMapper.updateSubsidyByBatchOrDetailNo(subsidy);


                            } else{


                                TransferBatches batches = new TransferBatches();
                                batches.setDetailNo(out_detail_no);
                                Date initiate_time_parse = null;
                                if(initiate_time != null){
                                    initiate_time_parse = DateUtils.parseDate(initiate_time, "yyyy-MM-dd'T'HH:mm:ssXXX");
                                    batches.setInitiateTime(initiate_time_parse);
                                }
                                batches.setBatchStatus(batch_status);//批单状态
                                batches.setUpdateTime(detail_update_time_parse);//明细更新时间
                                batches.setWxDetailId(detail_id);//微信端明细单号
                                batches.setDetailStatus(detail_status);//明细状态
                                if(close_reason != null){
                                    batches.setCloseReason(close_reason);
                                }
                                batchesMapper.updateTransferBatchesByBatchNoOrDetailNo(batches);

                                // 如果转账成功就将补贴表状态修改
                                if(WxBatchDetailState.SUCCESS.getType().equals(detail_status)){
                                    Subsidy subsidy = new Subsidy();
                                    subsidy.setTransferBatchNo(out_batch_no);
                                    subsidy.setTransferDetailNo(out_detail_no);
                                    subsidy.setStatus("1");
                                    subsidy.setDrawTime(initiate_time_parse);
                                    subsidyMapper.updateSubsidyByBatchOrDetailNo(subsidy);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("执行完成");
                }
            });
        }
    }



}
